package org.jasper.impl.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.UUID;

import static java.lang.Character.isWhitespace;


public class StringUtils {

    public static String uuid() {
        return "x" + UUID.randomUUID().toString().replace( '-', 'x' );
    }

    public static boolean isEmpty(final CharSequence str) {
        if ( str == null || str.length() == 0 ) {
            return true;
        }

        for ( int i = 0, length = str.length(); i < length; i++ ){
            if ( !isWhitespace(str.charAt( i )) )  {
                return false;
            }
        }

        return true;
    }

    public static String readFileAsString(Reader reader) {
        try {
            StringBuilder fileData = new StringBuilder( 1000 );
            char[] buf = new char[1024];
            int numRead;
            while ( (numRead = reader.read( buf )) != -1 ) {
                String readData = String.valueOf( buf,
                        0,
                        numRead );
                fileData.append( readData );
                buf = new char[1024];
            }
            reader.close();
            return fileData.toString();
        } catch ( IOException e ) {
            throw new RuntimeException( e );
        }
    }

    public static String toString(Reader reader) throws IOException {
        if ( reader instanceof BufferedReader) {
            return toString( (BufferedReader) reader );
        } else {
            return toString( new BufferedReader( reader ) );
        }
    }

    public static String toString(BufferedReader reader) throws IOException {
        StringBuilder sb = new StringBuilder();
        try {
            String line;
            boolean previousLine = false;
            while ((line = reader.readLine()) != null) {
                if ( previousLine ) {
                    sb.append("\n");
                }
                sb.append(line);
                previousLine = true;
            }
        } finally {
            reader.close();
        }
        return sb.toString();
    }
}
